package com.example.core.livedata

import android.util.Log
import androidx.annotation.MainThread
import androidx.annotation.Nullable
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import java.util.concurrent.atomic.AtomicBoolean


/**
 * Created by zhudongao
 * Desc
 * Date 2020/9/23
 */
class SingleLiveEvent<T> : MutableLiveData<T>() {
    private val TAG = "SingleLiveEvent"

    private val mPending: AtomicBoolean = AtomicBoolean(false)

    @MainThread
    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        if (hasActiveObservers()) {
            Log.w(TAG, "Multiple observers registered but only one will be notified of changes.")
        }
        super.observe(owner, Observer<T> { data ->
            if (mPending.compareAndSet(true, false)) {
                observer.onChanged(data)
            }
        })
    }

    /**
     * modify by bzb
     * 当 setValue时 mPending.set(true) compareAndSet(true,false) （true(set(true)后的“原值”) == true(except 值)）=true  -> mPending.set(false（update值）)  所以 再次 observer
     * 时 该值为false 所以不会执行 onChanged（t）方法
     * @param t
     */
    @MainThread
    override fun setValue(@Nullable t: T?) {
        mPending.set(true)
        super.setValue(t)
    }

    /**
     * Used for cases where T is Void, to make calls cleaner.
     */
    @MainThread
    fun call() {
        value = null
    }
}